<?php

namespace App\Http\Controllers\Finance;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Finance\FinanceCustomerBill;
use App\Models\Finance\FinanceShopSubAccountBill;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\FinanceBillMonthAllExport;
use Illuminate\Support\Facades\Storage;
use App\Exports\FinanceBillDetailExport;

class FinanceBillExcelController extends Controller
{
    use ResponseData;

    //
    public function exportCutomerOfficialBill(Request $request){
        $bill=FinanceCustomerBill::with($this->detailWith())
            ->find($request->id??0);
        if(empty($bill)){
            return $this->failed('id错误，无此账单',201);
        }
        $detailExport=new FinanceBillDetailExport();
        $excelUrl=$detailExport->exportBillDetailExcel($bill);
        return $this->success($excelUrl);
    }
    //
    public function detailWith(){
        return [
            'accountBills',
            'customer',
//            'branchBills',
        ];
    }

    //导出某个月子账号全部 正式 账单
    public function exportMonthAll(Request $request){
        $month=$request->year_month;
        $bids=$this->getOfficialBids($month);
        $collections=FinanceShopSubAccountBill::whereIn('bill_id',$bids)->get();
        $realMonth=$month??date('Y-m',strtotime('-1 month'));
        //文件名
        $excelName=$realMonth.'账单导出'.date('YmdHis').'.xlsx';
        //存储目录
        $excelStorePath='public/export/'.date('Y').'/'.date('m');
        Storage::makeDirectory($excelStorePath);
        $excelStoreName=$excelStorePath.'/'.$excelName;
        Excel::store(new FinanceBillMonthAllExport($collections), $excelStoreName);
        //web读取目录
        $excelWebPath='storage/export/'.date('Y').'/'.date('m');
        return $this->success(['excel_url'=>config('app.url').$excelWebPath.'/'.$excelName]);
    }
    //
    public function subBillsWith(){
        return [
            'shop',
            'subAccount',
            'customer',
        ];
    }
    //某个月所有正式账单的id
    public function getOfficialBids($month){
        return FinanceCustomerBill::where(function (Builder $query) use($month) {
            if($month){
                $query->where('bill_date', '=', $month);
            }else{
                $query->where('bill_date', '=', date('Y-m'))
                    ->orWhere('bill_date', '=', date('Y-m',strtotime('-1 month')));
            }
        })
            ->where('bill_status',2)
            ->pluck('id');
    }

    //客户账单详情
    public function billShow(Request $request){
        $bill=FinanceCustomerBill::with($this->detailWith())
            ->find($request->bill_id??0);
        if(empty($bill)){
            return $this->failed('id错误，无此账单',201);
        }
        return $this->success($bill);
    }

    //更新客户总账单
    public function updateCustomerBill(Request $request){
        $bill=FinanceCustomerBill::find($request->bill_id??0);
        if(empty($bill)){
            return $this->failed('id错误，无此账单',201);
        }
        $data=$request->except('bill_id');
        $bill->update($data);
        return $this->success('更新成功');
    }

    //更新账单子账号详细信息
    public function updateShopSubAccountBill(Request $request){
        $accountBill=FinanceShopSubAccountBill::find($request->account_bill_id??0);
        if(empty($accountBill)){
            return $this->failed('id错误，无此账单',201);
        }
        $data=$request->except('account_bill_id');

//        $data=$this->getTotalReceive($data);

        $accountBill->update($data);

        $this->updateBillTotal($accountBill);

        return $this->success('更新成功');
    }
    //计算回款项总和
    public function getTotalReceive($data){
        $data['all_received']=($data['pdd_received']??0)
            +($data['previous_reserved']??0)
            +($data['deposit_cost']??0)
            +($data['other_received']??0);
        return $data;
    }

    //统计总账单数据
    public function updateBillTotal($accountBill){
        $totalData=$this->calcData($accountBill);
        return $accountBill->bill()->update($totalData);
    }
    //获取总账单数据
    public function calcData($accountBill){
        return [
            'total_service_days'=>$this->sumColumnData($accountBill->bill_id,'service_days'),
            'total_consult'=>$this->sumColumnData($accountBill->bill_id,'consult_quantity'),
//            'day_average_consult'=>$this->sumColumnData($accountBill->bill_id,'service_days'),
//            'this_period_total'=>$this->sumColumnData($accountBill->bill_id,'all_this_period_fee'),
//            'previous_period_receivable'=>$this->sumColumnData($accountBill->bill_id,'previous_receivable'),
//            'received_total'=>$this->sumColumnData($accountBill->bill_id,'all_received'),
//            'total_customer_pay'=>$this->sumColumnData($accountBill->bill_id,'customer_period_pay'),
        ];
    }
    //计算各子账号数据总和
    public function sumColumnData($billId,$column){
        return FinanceShopSubAccountBill::where('bill_id',$billId)->sum($column);
    }


}
